<?php

namespace App\Repositories;

use App\Http\Helper\BeanHelper;
use App\Models\WechatUser;
use App\Models\LogHelper;
use App\Services\Thirdparty\QieziAccountCenterAuth;
use TestingDevUrlService;
use TestingConfig;
use DB;

class WechatUserRepository extends Repository{

    static $tag = 'testing.user';

    public function store($data)
    {
        $res = WechatUser::firstOrCreate($data);

        return $res;
    }

    /**
     * 根据uid获取用户信息
     * @param $uid int
     * @return array
     */
    public function getByUid($uid){
        $cacheKey = getCacheKey('testing.cache_key.user.info').$uid;
        $data = $this->remember($cacheKey, function () use ($uid) {
            return BeanHelper::convertStdClsToArr(
                WechatUser::where('uid', $uid)->first()
            );
        });
        return $data;
    }

    /**
     * 根据用户手机号获取用户信息
     * @param $phone
     * @return mixed
     */
    public function getByPhone($phone) {
        return BeanHelper::convertStdClsToArr(
            WechatUser::where('phone', $phone)->first()
        );
    }

    public function getNickNameByUid($uid){
        $cacheKey = getCacheKey('testing.cache_key.user_recode.nick_name').$uid;
        $data = $this->remember($cacheKey, function () use ($uid) {
            $res = WechatUser::select('nick_name')->where('uid', $uid)->first();
            return $res['nick_name'];
        });
        return $data;
    }

    /**根据uid,appid查找用户openid
     * @param $uid
     * @param $appid
     * @return mixed
     */
    public function getByUidAppid($uid,$appid){
        $cacheKey = getCacheKey('testing.cache_key.user.info').$uid.$appid;
        $data = $this->remember($cacheKey, function () use ($uid,$appid) {
            return WechatUser::select('openid')->where('uid', $uid)->where('from_appid',$appid)->first();
        });
        return $data;
    }

    /**根据appid获取uid集合
     * @param $appid
     * @return mixed
     */
    public function getUsersByAppid($appid){
        $cacheKey = getCacheKey('testing.cache_key.user.appid').$appid;
        $data = $this->remember($cacheKey, function () use ($appid) {
            return WechatUser::where('from_appid',$appid)->pluck('uid');
        });
        return $data;
    }

    /**
     * 公共开放接口，帐号中心微信授权
     * @param $developerCode string 开发者唯一识别码
     * @param $callbackUrl string 开发者回调url
     */
    public function qieziAccountCenterWechatAuth($developerCode, $callbackUrl,$authorize_appid){
        $urlId = TestingDevUrlService::fetchRedirectUrlInfoId($callbackUrl,$developerCode);
        $instance = new QieziAccountCenterAuth($urlId,$authorize_appid);
        $instance->wechatAuth();
    }


    /**
     * 公共开放接口，帐号中心手机号码授权
     * @param $developerCode string 开发者唯一识别码
     * @param $callbackUrl string 开发者回调url
     */
    public function qieziAccountCenterMobileAuth($developerCode, $callbackUrl,$authorize_appid){
        $urlId = TestingDevUrlService::fetchRedirectUrlInfoId($callbackUrl,$developerCode);
        $instance = new QieziAccountCenterAuth($urlId,$authorize_appid);
        $instance->mobileAuth();
    }


    /**
     * 从帐号中心获取用户信息并保存到本地的用户数据库
     * @param $uid string 用户id
     * @param $devUrlInfo object 第三方平台的回调url
     * @param $authorize_appid
     * @return array $userInfo
     */
    public function checkAccountCenterUserInfo($uid, $devUrlInfo, $authorize_appid){
        LogHelper::log("checkAccountCenterUserInfo==========>");
        $instance = new QieziAccountCenterAuth($devUrlInfo['id'],$authorize_appid );
        if(!$userInfo = $this->getByUid($uid)){
            LogHelper::log("user not exists");
            $userInfo = $instance->getAccountUserFromRedis($uid);

            LogHelper::log("checkAccountCenterUserInfo==========>");
            if(!empty($userInfo)){
                //添加来源地址
                $userInfo['union_code'] = $devUrlInfo['union_code'];
                $userInfo['from_url'] = $devUrlInfo['redirect_url'];
                $userInfo['from_url'] = $devUrlInfo['redirect_url'];
                $this->store($userInfo);
            }

            LogHelper::log($userInfo,'auth_user');

        }else{
            //清除用户的缓存
            $this->clearUserInfoCache($userInfo);
            $accountUser = $instance->getAccountUserFromRedis($uid);
            $this->updateByUid($uid,$accountUser);
        }
        return $userInfo;
    }


    /**
     * 通过openId获取用户信息
     */
    public function getByOpenId($openId){
        $cacheKey = getCacheKey('testing.cache_key.user.info');
        $key = $cacheKey.$openId;
        $cate = $this->remember($key, function () use ($openId) {
            return WechatUser::where('openid', $openId)->first();
        });
        return $cate;
    }
    /**
     * 通过union_id获取用户信息
     */
    public function getByUnionId($unionId){
        $cacheKey = getCacheKey('testing.cache_key.user.info');
        $key = $cacheKey.$unionId;
        $data = $this->remember($key, function () use ($unionId) {
            return BeanHelper::convertStdClsToArr(WechatUser::where('wx_union_id', $unionId)->first());
        });
        return $data;
    }

    /**
     * 构建用户头像地址
     */
    public function buildUserAvatarUrl($avatar){
        $accountUrl = TestingConfig::getValue('account.account_center_url');
        $avatarMidFix = TestingConfig::getValue('account.avatar.middle_fix');
        $url = $accountUrl.$avatarMidFix.$avatar;
        return $url;
    }

    /**
     * @deprecated
     * 从cookie中获取用户信息
     */
    public function getQieziAccountCenter($request){
        $instance = new QieziAccountCenterAuth();
        $user = $instance->getAccountCenterUser($request);
        $userObj = $this->getByOpenId($user['openid']);
        if(!$userObj){
            $data['openid'] = $user['openid'];
            $data['uid'] = $user['uid'];
            $data['nick_name'] = $user['nick_name'];
//            $data['sex'] = $user['sex'];
            $data['headimgurl'] = $user['headimgurl'];
            $data['province'] = $user['province'];
            $data['city'] = $user['city'];
            $data['country'] = $user['country'];
            $this->store($data);
        }
        return $userObj['uid'];
    }


    /**
     * 根据用户编号更新用户信息
     * @param $uid 用户编号
     * @param $data 用户信息
     * @return mixed
     */
    public function updateByUid($uid, $data){
        $user = $this->getByUid($uid);
        //先删除缓存
        $this->clearUserInfoCache($user);
        return WechatUser::where('uid', $uid)->update($data);
    }

    /**
     * 某个字段值加1
     * @param $uid
     * @param $column
     * @return mixed
     */
    public function columnIncrement($uid, $column) {
        return WechatUser::where('uid', $uid)->increment($column);
    }

    public function clearUserInfoCache($userInfo){
        $cacheKey = getCacheKey('testing.cache_key.user.info');
        $key = $cacheKey.$userInfo['id'];
        $this->forget($key);
        $key = $cacheKey.$userInfo['openid'];
        $this->forget($key);
        $key = $cacheKey.$userInfo['uid'];
        $this->forget($key);
    }

    public function options(){
        $list = WechatUser::all();
//        $data = [];
//        if($list){
//            $obj = array();
//            foreach ($list as $key => $val){
//                $obj['id'] = $val['uid'];
//                $obj['text'] = $val['nick_name'];
//                array_push($data,$obj);
//            }
//        }
        return $list;
    }

    public function getUserChannelCode($uid) {
        $user = WechatUser::select('channel_code')->where('uid', $uid)->first();
        if ($user) {
            return $user['channel_code'];
        }
        return '';
    }

    public function model()
    {
        return app(WechatUser::class);
    }

    public function tag()
    {
        return self::$tag;
    }
}